package com.ypf.demo_ssm.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ypf.demo_ssm.config.ServiceException;
import com.ypf.demo_ssm.dto.request.UserDTO;
import com.ypf.demo_ssm.dto.response.OrderVO;
import com.ypf.demo_ssm.dto.response.UserOrdersVO;
import com.ypf.demo_ssm.entity.User;
import com.ypf.demo_ssm.mapper.UserMapper;
import com.ypf.demo_ssm.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ypf.demo_ssm.utils.LocalDateConverter;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 殷鹏飞
 * @since 2024-06-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public List<User> queryList(String username, String account) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .like(StringUtils.isNotBlank(username), "username", username)
                .like(StringUtils.isNotBlank(account), "account", account);
        return userMapper.selectList(queryWrapper);
    }

    @Override
    public boolean addOrUpdate(User user) {
        // 新增 该方法会检查给定的字符串是否为null或空字符串（""）
        if (StringUtils.isEmpty(user.getId())) {
            if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getAccount())) {
                throw new ServiceException("名称和账号不能为空");
            }
            if (accountExists(user.getAccount())) {
                throw new ServiceException("账号已存在");
            }
            return userMapper.insert(user) > 0;
        }
        // 更新
        return userMapper.updateById(user) > 0;
    }

    /**
     * 判断账号是否已存在
     */
    @Override
    public boolean accountExists(String account) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        return this.count(queryWrapper) > 0;
    }

    @Override
    public void importExcel(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), User.class, new PageReadListener<User>(dataList -> {
                    for (User user : dataList) {
                        System.out.println("导入的数据: " + JSON.toJSONString(user));
                        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getAccount())) {
                            throw new ServiceException("名称和账号不能为空");
                        }
                        if (accountExists(user.getAccount())) {
                            throw new ServiceException(user.getUsername() + " 账号已存在");
                        }
                        userMapper.insert(user);
                    }
                }))
                .registerConverter(new LocalDateConverter()) // 使用自定义转换器
                .sheet()
                .doRead();
    }

    @Override
    public void exportExcel(OutputStream outputStream) {
        List<User> users = list(); // 获取数据
        EasyExcel.write(outputStream, User.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("用户信息")
                .doWrite(users);
    }

    @Override
    public List<UserOrdersVO> selectUserAndOrders(UserDTO userDTO) {
        List<UserOrdersVO> list = userMapper.selectUserAndOrders(userDTO);
        for (UserOrdersVO userOrdersVO: list) {
            if (StringUtils.isNotBlank(userOrdersVO.getOrderListStr())) {
                // 使用FastJSON将JSON字符串转为List
                userOrdersVO.setOrderList(JSON.parseArray(userOrdersVO.getOrderListStr(), OrderVO.class));
            } else {
                // 设置为空列表而非null
                userOrdersVO.setOrderList(new ArrayList<>());
            }
        }
        return list;
    }


}
